<?php

namespace app\admin\controller;

use app\common\model\Role as RoleModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;

/**
 * 角色管理
 * Class Role
 * @package app\admin\controller
 */
class Role extends AdminBase
{
    protected $role_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->role_model = new RoleModel();
    }

    /**
     * 角色管理
     * @param string $keyword
     * @param int $page
     * @return mixed
     */
    public function index($keyword = '', $page = 1)
    {
        $map = [];
        if ($keyword) {
            $map['name'] = ['like', "%{$keyword}%"];
        }
        $role_list = $this->role_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['role_list' => $role_list, 'keyword' => $keyword]);
    }

    /**
     * 添加角色
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存角色
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'Role'); // 这边会变成 os_name 表？？？ 待查错

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->role_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑角色
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $role = $this->role_model->find($id);

        return $this->fetch('edit', ['role' => $role]);
    }

    /**
     * 更新角色
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'Role');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $role = $this->role_model->find($id);
                $role->id = $id;
                $role->name = $data['name'];
                $role->status = $data['status'];
                $role->update_time = time();
                if ($role->save() !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除角色  --- 正常需要检测角色下是否存在用户
     * @param $id
     */
    public function delete($id)
    {
        if ($this->role_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}